#include "head_s.h"

int download(const user_t* status, const portocol_t* portocol, int net_fd, MYSQL* mysql)
{
    char file_name[60] = {0};
    char file_path[128] = {0};
    sprintf(file_name, "%s", status->arg);
    sprintf(file_path, "%s%s",  status->path, file_name);
    //printf("gets: %s\n", file_name);
    //printf("gets: %s\n", file_path);

    //根据用户名在用户表查询用户id
    char search_id[128] = {0};
    //printf("gets.c: 14 : %s\n", status->user_name);
    sprintf(search_id, "select id from user_info where name = '%s'", status->user_name);
    //printf("gets.c: 16 : %s\n", search_id);
    if (mysql_query(mysql, search_id))
    {
        printf("%s\n", mysql_error(mysql));
    }
    MYSQL_RES* result;
    result = mysql_store_result(mysql);
    MYSQL_ROW row = mysql_fetch_row(result);
    int user_id = atoi(row[0]);
    //printf("gets.c: 24: user_id = %d\n", user_id);
    mysql_free_result(result);
    
    //根据用户id在文件表查找对应文件名的哈希值
    char search_hash[255] = {0};
    sprintf(search_hash, "select file_hash from file_info "
                         "where user_id = %d and file_name = '%s' and file_path = '%s'",
                          user_id, file_name, file_path);
    if (mysql_query(mysql, search_hash))
    {
        printf("%s\n", mysql_error(mysql));
    }
    result = mysql_store_result(mysql);
    my_ulonglong row_num = mysql_num_rows(result);
    //无对应文件
    if (result == NULL || row_num == 0)
    {
        //printf("gets.c: 42: 11111\n");
        send(net_fd, "1", 1, MSG_NOSIGNAL);
        return -1;
    }
    
    send(net_fd, "0", 1, MSG_NOSIGNAL);
    row = mysql_fetch_row(result);
    char hash[128] = {0};
    sprintf(hash, "%s%s", status->base_path, row[0]);
    //printf("gets.c: 48: %s\n", hash);
    
    mysql_free_result(result);
    
    int file_fd = open(hash, O_RDWR);
    //printf("gets.c: 54: %s\n", file_name);
    int file_name_len = strlen(file_name);
    //printf("gets.c: 56: %d\n", file_name_len);
    send(net_fd, &file_name_len, sizeof(int), MSG_NOSIGNAL);
    send(net_fd, file_name, file_name_len, MSG_NOSIGNAL);
    
    struct stat st;
    fstat(file_fd, &st);
    size_t file_size = st.st_size;
    //printf("gets.c: 63: %ld\n", file_size);
    send(net_fd, &file_size, sizeof(size_t), MSG_NOSIGNAL);
    //int is_exist = 0;
    //recv(net_fd, &is_exist, sizeof(int), MSG_WAITALL);
    //说明文件为断点续传
   /* if (is_exist == -1)
    {
        off_t curr_size = 0;
        recv(net_fd, &curr_size, sizeof(off_t), MSG_WAITALL);
        printf("curr_size = %ld\n", curr_size);
        struct stat st;
        fstat(file_fd, &st);
        off_t need_size = st.st_size - curr_size;
        printf("need_size = %ld\n", need_size);
        send(net_fd, &need_size, sizeof(off_t), MSG_NOSIGNAL);
        sendfile(net_fd, file_fd, &curr_size, need_size);
        return 0;
    }*/
    sendfile(net_fd, file_fd, 0, file_size);
    //printf("%d\n", send_size);

    return 0;
}
